import type { TableColumnCtx } from 'element-plus';

import type { Dict } from '@croco/framework/types';

import type { DataFormItemProps, DataFormSchema } from '#/components/data-form';
import type { FieldProps, OnActionClickFn, RenderScope } from '#/components/data-table';

import { h, reactive } from 'vue';

import { useAccess } from '@croco/framework/access';
import { $t } from '@croco/framework/locales';

import { ElSwitch, ElText } from 'element-plus';

import { service } from '#/api/request';

const { hasPermission } = useAccess();

const isChangeStatus = hasPermission('quartz:job:status');

export function useTable(enums: Record<string, Array<Dict> | undefined>, onActionClick: OnActionClickFn): FieldProps[] {
    const formatter = (row: any, column: TableColumnCtx) => {
        switch (column.property) {
            case 'beanName': {
                return `${row.beanName}.${row.methodName}(${row.params ?? ''})`;
            }
            case 'concurrent':
            case 'groupName':
            case 'misfirePolicy': {
                const dict = enums[column.property]?.find((item) => item.value === row[column.property]);
                return h(ElText, { type: dict?.listClass || 'info' }, { default: () => dict?.label || '--' });
            }
            case 'status': {
                return h(ElSwitch, {
                    modelValue: row[column.property],
                    'onUpdate:modelValue': (newValue) => {
                        row[column.property] = newValue;
                    },
                    style: `--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;`,
                    activeValue: '1',
                    inactiveValue: '0',
                    inlinePrompt: true,
                    activeText: '运行',
                    inactiveText: '暂停',
                    disabled: !isChangeStatus,
                    'before-change': () => {
                        return new Promise((resolve, reject) => {
                            service.confirm({
                                message: '确定要切换任务状态吗？',
                                url: `/job/${row.status === '1' ? 'pause' : 'resume'}`,
                                type: 'get',
                                data: {
                                    id: row.id,
                                },
                                success: () => {
                                    resolve(true);
                                },
                                failure: () => {
                                    reject(new Error('已取消操作'));
                                },
                            });
                        });
                    },
                });
            }
            default: {
                return '';
            }
        }
    };

    return [
        { prop: 'name', label: '名称', search: true, column: { width: 250, showOverflowTooltip: true } },
        { prop: 'groupName', label: '分组名称', search: { value: '' }, column: { width: 180, formatter } },
        { prop: 'beanName', label: '调用函数', search: true, column: { width: 350, showOverflowTooltip: true, formatter } },
        { prop: 'misfirePolicy', label: '执行策略', column: { width: 100, align: 'center', formatter } },
        { prop: 'cronExpression', label: 'Cron表达式', column: { width: 200 } },
        { prop: 'concurrent', label: '并发执行', column: { visible: false, width: 100, align: 'center', formatter } },
        { prop: 'status', label: '状态', search: { value: '' }, column: { width: 110, align: 'center', formatter } },
        { prop: 'remark', label: '备注', column: { minWidth: 300, showOverflowTooltip: true } },
        { prop: 'createTime', label: '创建时间', column: { visible: false, width: 190 } },
        {
            column: {
                width: 150,
                maxCollapseButtons: 2,
                render: [
                    { auth: 'quartz:job:edit', onClick: (scope: RenderScope) => onActionClick({ code: 'edit', scope }) },
                    { auth: 'quartz:job:remove', onClick: (scope: RenderScope) => onActionClick({ code: 'remove', scope }), type: 'danger' },
                    { auth: 'quartz:job:run', onClick: (scope: RenderScope) => onActionClick({ code: 'run', scope }) },
                    { auth: 'quartz:job:log:list', onClick: (scope: RenderScope) => onActionClick({ code: 'log', scope }) },
                ],
            },
        },
    ];
}

export function useLogTable(enums: Record<string, Array<Dict> | undefined>): FieldProps[] {
    const formatter = (row: any, column: TableColumnCtx) => {
        switch (column.property) {
            case 'beanName': {
                return `${row.beanName}.${row.methodName}(${row.params ?? ''})`;
            }
            case 'groupName':
            case 'status': {
                const field = column.property === 'status' ? 'result' : column.property;
                const dict = enums[field]?.find((item) => item.value === row[column.property]);
                return h(ElText, { type: dict?.listClass || 'info' }, { default: () => dict?.label || '--' });
            }
            default: {
                return '';
            }
        }
    };

    return [
        { prop: 'id', label: '日志ID', column: { width: 90 } },
        { prop: 'groupName', label: '分组名称', column: { minWidth: 250, formatter } },
        { prop: 'beanName', label: '调用函数', column: { width: 450, showOverflowTooltip: true, formatter } },
        { prop: 'status', label: '状态', search: { value: '' }, column: { width: 100, align: 'center', formatter } },
        { prop: 'error', label: '错误信息', column: { width: 650, showOverflowTooltip: true } },
        { prop: 'costTime', label: '耗时（毫秒）', column: { width: 190 } },
        { prop: 'createTime', label: '创建时间', column: { width: 190 } },
    ];
}

export function useForm(): DataFormSchema {
    const rules = reactive({
        name: [{ required: true, message: $t('ui.formRules.required'), trigger: 'blur' }],
        beanName: [{ required: true, message: $t('ui.formRules.required'), trigger: 'blur' }],
        methodName: [{ required: true, message: $t('ui.formRules.required'), trigger: 'blur' }],
        cronExpression: [{ required: true, message: $t('ui.formRules.required'), trigger: 'blur' }],
    });
    const fields: DataFormItemProps[] = [
        { prop: 'id', primary: true },
        { prop: 'name', label: '名称', slot: 'name' },
        { prop: 'groupName', label: '分组名称', slot: false, multiple: false, value: '' },
        { prop: 'cronExpression', label: 'Cron表达式' },
        { prop: 'beanName', label: '服务名称', slot: 'beanName' },
        { prop: 'methodName', label: '函数名称', slot: false },
        { prop: 'params', label: '运行参数', slot: 'params' },
        { prop: 'misfirePolicy', label: '执行策略', slot: 'misfirePolicy' },
        { prop: 'concurrent', label: '并发执行', slot: false },
        { prop: 'status', label: '状态', slot: false, multiple: false, value: '' },
        { prop: 'remark', label: '备注' },
    ];
    return { rules, fields, isChangeStatus };
}
